/**
 * @modal: 智能策略自动配置
 */
import { useEffect, useState } from "react";
import { DatePicker, Radio, Form, Switch, InputNumber } from "antd";
import CommonInput from '@/pages/OrderModule/common/components/CommonInput';
import Iconfont from "@/components/IconFont";
import BatchInputModal from '../../../../../../common/components/BatchInputModal2';
import moment from 'moment';

const { RangePicker } = DatePicker;

function ExecuteRecord({ strategyData, formRef }) {

	const [form] = Form.useForm();
	const { enableAuto, timeType, timePoint, timeStart, timeEnd, timeInterval, validityDateType, validityStartDate, validityEndDate } = strategyData;
	const useDateType = Form.useWatch('validityDateType', form);
	const useTimeType = Form.useWatch('timeType', form);

	const [open, setOpen] = useState(false);

	useEffect(() => {
		form.resetFields();
	}, [enableAuto, timeType, validityDateType])

	//校验数字
	const validatorNum =  (_, value) => {
		if (!value && value != 0) {
			return Promise.reject(new Error('请输入'));
		}
		return Promise.resolve();
	}

	//批量输入
	const BatchInputModalProps = {
		label: '请输入执行时间',
		handleOk(val) {
			form.setFieldsValue({
				timePoint: val
			})
			setOpen(false);
		},

		handleCancel() {
			setOpen(false);
		}
	}

	const formatterFunc = (val, min, max) => {
		let realVal = val?.replaceAll(' ', '') || '';
		if(realVal){
			if(realVal?.length == 1){
				realVal = 0 + realVal;
			}else{
				realVal = Math.max(realVal, min);
				realVal = Math.min(realVal, max);
			}
		}
		return realVal;
	}

	return (
		<>
			<Form
				name="auto-config-form"
				form={form}
				autoComplete="false"
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 20 }}
				initialValues={{
					timeType,
					enableAuto,
					validityDateType,
					timeInterval,
					timePoint,
					timeStartHour: timeStart ? timeStart.split(':')[0] : undefined,
					timeStartMinutes: timeStart ? timeStart.split(':')[1] : undefined,
					timeEndHour: timeEnd ? timeEnd.split(':')[0] : undefined,
					timeEndMinutes: timeEnd ? timeEnd.split(':')[1] : undefined,
					validityDate: validityStartDate ? [moment(validityStartDate), moment(validityEndDate)] : []
				}}
				style={{ margin: '12px 0' }}
			>
				<div style={{ display: 'flex',alignItems: 'baseline' }}>
					<h3 style={{ margin: '0 32px 12px 0' }}>1、自动执行是否开始</h3>
					<Form.Item
						name="enableAuto"
						valuePropName="checked"
						noStyle
					>
						<Switch checkedChildren="已开启" unCheckedChildren="已关闭" />
					</Form.Item>
				</div>
				<div>
					<h3 style={{ margin: '12px 0' }}>2、自动执行时间</h3>
					<Form.Item label="任务有效期" name="validityDateType">
						<Radio.Group>
							<Radio value={1}>长期有效</Radio>
							<Radio value={2}>指定时间</Radio>
						</Radio.Group>
					</Form.Item>
					{
						useDateType == 2 ?
							<Form.Item label=" " colon={false} name="validityDate" style={{ marginTop: '-12px' }} rules={[{
								validator: (_, value) => {
									if (value && value.length == 0) {
										return Promise.reject(new Error('请选择时间'));
									}
									return Promise.resolve();
								}
							}]}>
								<RangePicker format="YYYY-MM-DD" />
							</Form.Item> : null
					}
					<Form.Item label="任务执行时间" name="timeType">
						<Radio.Group>
							<Radio value={1}>定时执行</Radio>
							<Radio value={2}>指定时间点执行</Radio>
						</Radio.Group>
					</Form.Item>
					{
						useTimeType == 1 ?
							<Form.Item label=" " colon={false} style={{ marginTop: '-12px' }} >
								<div style={{ display: 'flex', alignItems: 'center' }} >
									<Form.Item label="" colon={false} name="timeStartHour" style={{ marginBottom: 0 }} rules={[{ validator: validatorNum}]}>
										<InputNumber controls={false} precision={0} style={{ width: 60 }} formatter={(val)=>formatterFunc(val, 0, 23)}/>
									</Form.Item>
									：
									<Form.Item label="" colon={false} name="timeStartMinutes" style={{ marginBottom: 0 }} rules={[{ validator: validatorNum}]}>
										<InputNumber controls={false} precision={0} style={{ width: 60 }} formatter={(val)=>formatterFunc(val, 0, 59)}/>
									</Form.Item>
									<span style={{ margin: '0 8px' }}>至</span>
									<Form.Item label="" colon={false} name="timeEndHour" style={{ marginBottom: 0 }} rules={[{ validator: validatorNum}]}>
										<InputNumber controls={false} precision={0} style={{ width: 60 }} formatter={(val)=>formatterFunc(val, 0, 23)}/>
									</Form.Item>
									：
									<Form.Item label="" colon={false} name="timeEndMinutes" style={{ marginBottom: 0 }} rules={[{ validator: validatorNum}]}>
										<InputNumber controls={false} precision={0} style={{ width: 60 }} formatter={(val)=>formatterFunc(val, 0, 59)}/>
									</Form.Item>
									<span style={{ marginRight: '8px' }}>，每间隔</span>
									<Form.Item label="" colon={false} name="timeInterval" style={{ marginBottom: 0 }} rules={[{ validator: validatorNum}]}>
										<InputNumber controls={false} precision={0} min={1} max={9999} style={{ width: 60 }} />
									</Form.Item>
									<span style={{ marginLeft: '8px' }}>分钟执行</span>
								</div>
							</Form.Item> : null
					}
					{
						useTimeType == 2 ?
							<Form.Item label=" " style={{ marginTop: '-12px' }} colon={false} name="timePoint" extra="多个逗号隔开，例如（9:00,10:00,12:00），注意使用英文符号" rules={[{
								validator: (_, value) => {
									if (!value) {
										return Promise.reject(new Error('请输入执行时间'));
									}
									if(!/^[0-9\:\：\,\，]+$/.test(value)) {
										return Promise.reject(new Error('输入格式错误'));
									}
									return Promise.resolve();
								}
							}]}>
								<CommonInput placeholder="请输入执行的时间点" suffix={<Iconfont type="icondirect-input" onClick={() => setOpen(true)} />} />
							</Form.Item> : null
					}
				</div>
			</Form>
			{ open && <BatchInputModal { ...BatchInputModalProps } />}
		</>
	);
}

export default ExecuteRecord;
